﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PatternFlyWeight
{
    class Program
    {
        static void Main(string[] args)
        {
            BikeFlyWeight bike1 = BikeFlyWeightFactory.GetInstance().GetBike();
            bike1.Ride("zhangsan");
            bike1.Back();

            BikeFlyWeight bike2= BikeFlyWeightFactory.GetInstance().GetBike();
            bike2.Ride( "zhangsan2");
            //bike2.Back();

            BikeFlyWeight bike3 = BikeFlyWeightFactory.GetInstance().GetBike();
            bike3.Ride( "zhangsan3");
            bike3.Back();


            Console.ReadKey  ();
        }
    }
     
    abstract class BikeFlyWeight
    {
        protected int state  ;

        public abstract void Ride(string userName);
        public abstract void Back();
         
        public int GetState()
        { return state; }
    
    }

    class Bike : BikeFlyWeight
    {
        private string bikeId;
        public Bike(string _bikeId)
        {
            bikeId = _bikeId;
        } 
        public override void Back()
        {
            state = 0; 
        } 
        public override void Ride(string userName)
        {
            state = 1;
            Console.WriteLine(userName + " is using "+ bikeId); ;
        }
    }

    class BikeFlyWeightFactory
    {
        static BikeFlyWeightFactory instance = new BikeFlyWeightFactory();
        List<Bike> bikes =new List<Bike>();
        public BikeFlyWeightFactory()
        {
            for (int i = 0; i <= 3; i++)
            {
                bikes.Add(new Bike(i.ToString()));
            }
        } 
        public static BikeFlyWeightFactory GetInstance()
        {
            return instance;
        }  
        public BikeFlyWeight GetBike()
        { 
            foreach (BikeFlyWeight bike in bikes)
            {
                if (bike.GetState() == 0)
                { return bike; }
            }
            return null;
        }
         
    }

}
